package com.lihepeng.leecode.recursive;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 增加了子集问题
 */
public class Solution40 {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> item = new LinkedList<>();
    int pathSum =0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates,0,target);
        return result;
    }
    private void dfs(int[]candidates,int start,int target) {
        if (pathSum ==target) {
            // 退出条件
            result.add(new ArrayList<>(item));
            return;
        }
        if (pathSum > target) {
            return;
        }
        for (int i=start;i<candidates.length;i++) {
            // 剪枝
            if (i>start && candidates[i] == candidates[i-1]) {
                continue;
            }
            item.addLast(candidates[i]);
            pathSum+=candidates[i];
            dfs(candidates,i+1,target);
            item.removeLast();
            pathSum -=candidates[i];
        }
    }
}
